package cn.growthgate.fgo.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import cn.growthgate.fgo.common.base.BaseServiceImpl;
import cn.growthgate.fgo.entity.UserRole;
import cn.growthgate.fgo.entity.enums.Role;
import cn.growthgate.fgo.mapper.UserRoleMapper;
import cn.growthgate.fgo.service.IUserRoleService;
import cn.growthgate.fgo.util.CollectionUtils;

/**
 * <p>
 * 用户权限表 服务实现类
 * </p>
 *
 * @author GrowthGate
 * @since 2019-01-23
 */
@Service
public class UserRoleServiceImpl extends BaseServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

	@Override
	public List<Role> getRoles(Long userId) {
		List<UserRole> userRoles = baseMapper.selectList(newWrapper().eq("userId", userId));
		return userRoles.stream().map(userRole -> userRole.getRole()).collect(Collectors.toList());
	}

	@Override
	public boolean saveRoles(Long userId, Role[] roles) {
		// 新权限
		List<Role> nRoles = Arrays.asList(roles);
		// 旧权限
		List<Role> oRoles = getRoles(userId);
		// 需要添加的权限
		List<Role> iRoles = (List<Role>) CollectionUtils.subtract(nRoles, oRoles);
		// 需要删除的权限
		List<Role> dRoles = (List<Role>) CollectionUtils.subtract(oRoles, nRoles);
		// 添加权限
		if (CollectionUtils.isNotEmpty(iRoles)) {
			List<UserRole> iUserRoles = new ArrayList<>(iRoles.size());
			for (Role role : iRoles) {
				UserRole userRole = new UserRole();
				userRole.setUserId(userId);
				userRole.setRole(role);
				iUserRoles.add(userRole);
			}
			insertBatch(iUserRoles);
		}
		// 删除权限
		if (CollectionUtils.isNotEmpty(dRoles)) {
			delete(newWrapper().eq("userId", userId).in("role", dRoles));
		}
		return CollectionUtils.isNoneEmpty(iRoles, dRoles);
	}

}
